<template>
  <el-dialog
    top="30px"
    width="800px"
    title="反担保合同"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <el-form :rules="rules" ref="form" label-width="110px" :model="editData" v-loading="loading">
      <el-form-item label="保证人类型" prop="gua_entity_type" key="gua_entity_type">
        <c-select
          v-model="editData.gua_entity_type"
          class="form-control-ml"
          placeholder="请选择保证人类型"
          :options="enumEntityType"
        ></c-select>
      </el-form-item>
      <template v-if="+editData.gua_entity_type === 1">
        <el-form-item label="营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)" key="ocr">
          <upload-oss
            single-image
            :dir="dir"
            ref="uploadRegister"
            accept="image/*"
            :file-name="0"
            :file-list="registerList"
            :on-change="registerChange"
            :on-complete="handleUploadRegister"
          ></upload-oss>
        </el-form-item>
        <el-form-item label="股东会/董事会决议附件" prop="attachment" key="attachment">
          <upload-oss
            class="form-control-ml"
            :dir="dir"
            ref="attachment"
            :file-name="0"
            :file-list="attachmentList"
            :on-change="clearValidator"
            :on-complete="handleUploadAttachment"
          ></upload-oss>
        </el-form-item>
        <el-form-item label="公司名称" prop="gua_entity" key="gua_entity">
          <el-input
            v-model="editData.gua_entity"
            class="form-control-ml"
            placeholder="请输入公司名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人名字" prop="gua_entity_corp" key="gua_entity_corp">
          <el-input
            v-model="editData.gua_entity_corp"
            class="form-control-ml"
            placeholder="请输入负责人名字"
          ></el-input>
        </el-form-item>
        <el-form-item label="营业执照号" prop="gua_entity_cert_no" key="gua_entity_cert_no">
          <el-input
            v-model="editData.gua_entity_cert_no"
            class="form-control-ml"
            placeholder="请输入证件号"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="gua_entity_mobile" key="gua_entity_mobile">
          <el-input
            v-model="editData.gua_entity_mobile"
            class="form-control-ml"
            placeholder="请输入联系电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="经营地址" prop="gua_entity_address" key="gua_entity_address">
          <el-input
            v-model="editData.gua_entity_address"
            class="form-control-ml"
            placeholder="请输入经营地址"
          ></el-input>
        </el-form-item>
      </template>

      <el-form-item label="签约地点" prop="sign_address" key="sign_address">
        <el-input
          v-model="editData.sign_address"
          class="form-control-ml"
          placeholder="请输入签约地点"
        ></el-input>
      </el-form-item>
      <el-form-item label="合同共计" prop="num_copes_lower" key="num_copes_lower">
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_lower"
          placeholder="合同共计"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>
      <el-form-item
        label="甲方、乙方、借款人和贷款人各执"
        prop="num_copes_per_lower"
        key="num_copes_per_lower"
      >
        <el-input
          class="form-control-ml"
          v-model="editData.num_copes_per_lower"
          placeholder="甲方、乙方、借款人和贷款人各执"
          v-input-number="{ min: 0, fixed: 0 }"
        >
          <span slot="append">份</span>
        </el-input>
      </el-form-item>
      <el-form-item label="反担保人" v-if="+editData.gua_entity_type !== 1">
        <el-button size="mini" @click="addPerson()">
          <i class="fa fa-plus"></i>
          添加反担保人
        </el-button>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm bg-white table-vertical-middle text-center"
        >
          <colgroup>
            <col width="15%" />
            <col width="20%" />
            <col width="25%" />
            <col width="25%" />
            <col width="15%" />
          </colgroup>
          <tr>
            <td>反担保人</td>
            <td>联系电话</td>
            <td>身份证号</td>
            <td>联系地址</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of personData" :key="index">
            <td>{{ p.gua_person_name }}</td>
            <td>{{ p.gua_person_phone }}</td>
            <td>{{ p.id_card }}</td>
            <td>{{ p.gua_person_address }}</td>
            <td>
              <el-button type="text" @click="addPerson(p, index)">
                <i class="fa fa-edit"></i>
              </el-button>
              <el-button type="text" @click="deletePerson(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
          <tr v-if="!personData.length">
            <td colspan="5" class="text-muted">请添加反担保人</td>
          </tr>
        </table>
      </el-form-item>
      <el-form-item label="是否加盖公章" v-if="isSYSTEM || isRedo">
        <c-select
          class="form-control-ml"
          :options="{
            0: '不盖章(客户线下签约时选择)',
            1: '加盖公章',
          }"
          :number-key="true"
          v-model="signStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button class="btn-long" type="primary" @click="uploadAttachment" :loading="saveLoading">
          保存
        </el-button>
        <el-button class="btn-long" @click="beforeClose" :loading="saveLoading">取消</el-button>
      </el-form-item>
    </el-form>

    <promise-add
      :visible.sync="addVisible"
      :form-data="addData"
      :attach="addAttach"
      @back="setPerson"
    ></promise-add>
  </el-dialog>
</template>

<script>
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
import { mobileValidator } from '@/common/plugins/validator'
import { licenseValidate, nzhToNum, arrayFromString, arrayToString } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { getOrgInfo } from '@/credit/views/city/program/ocr/index'
import PromiseAdd from '@/credit/views/county/unionProvince/components/contractApproveDeploy/promise/PromiseAdd'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { attachAdapter } from '@/bank/components/attach/index'
export default {
  components: {
    PromiseAdd,
  },
  props: {
    visible: Boolean,
    isRedo: {
      // 是否合同重做，
      type: Boolean,
      default: false,
    },
    tableId: { type: String, default: '' },
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    const certNoValidator = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!licenseValidate(value)) {
        callback(new Error('错误的营业执照号，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      enumEntityType,
      editData: {
        gua_entity: '',
        gua_entity_type: '',
        gua_entity_corp: '',
        gua_entity_cert_no: '',
        gua_entity_mobile: '',
        gua_entity_address: '',
        sign_address: '',
        num_copes_lower: '',
        num_copes_per_lower: '',
        cert_attachment: '',
      },
      registerList: [],
      loading: false,
      rules: {
        gua_entity_type: { required: true, message: '请选择保证人类型', trigger: 'change' },
        gua_entity: { required: true, message: '请输入公司名称', trigger: 'blur' },
        gua_entity_corp: { required: true, message: '请输入负责人名字', trigger: 'blur' },
        gua_entity_mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: mobileValidator, message: '请输入正确的手机号码', trigger: 'blur' },
        ],
        gua_entity_address: [{ required: true, message: '请输入经营地址', trigger: 'blur' }],
        sign_address: [{ required: true, message: '请输入签约地点', trigger: 'blur' }],
        gua_entity_cert_no: [
          { required: true, message: '请输入证件号', trigger: 'blur' },
          { validator: certNoValidator, trigger: 'blur' },
        ],
        num_copes_lower: { required: true, message: '请输入合同份数', trigger: 'blur' },
        num_copes_per_lower: { required: true, message: '请输入合同份数', trigger: 'blur' },
        attachment: { required: true, message: '请上传股东会/董事会决议附件', trigger: 'change' },
      },
      tableName: 'gua_contract',
      saveLoading: false,
      personData: [],
      attachTable: 'datum_customer_attachment',
      attachs: [], // 所有保证合同附件

      addVisible: false,
      addAttach: [], // edit fileList
      addData: {},
      editIndex: -1,

      deleteAttach: [],

      attachmentList: [], // 股东会决议 2021.12.27
      signStatus: 1,
    }
  },
  computed: {
    ...mapGetters(['entrustContract', 'org']),
    dir() {
      return `credit/newProjec/promise_person/${this.editData.gua_entity_cert_no}`
    },
    queryId() {
      return this.relatedData.customer_related_id
    },
    isSYSTEM() {
      // 系统后台重做合同
      return this.org.orgClass === 'org_credit_sys'
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.deleteAttach = []

        this.attachmentList = arrayFromString(this.formData.attachment).map(url => {
          return attachAdapter({
            attachment: url,
          })
        })
        Object.keys(this.editData).forEach(key => {
          this.editData[key] = this.formData[key]
        })
        this.attachs = arrayFromString(this.formData.cert_attachment)
        if (this.attachs.length && +this.formData.gua_entity_type === 1) {
          this.registerList = [{ url: this.attachs?.[0] }]
        }
        this.getData()
      },
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    clearValidator() {
      this.$refs.form.clearValidate('attachment')
    },
    setPerson(person) {
      if (this.editIndex === -1) {
        this.personData.push(person)
      } else {
        this.personData[this.editIndex] = { ...person }
      }
    },
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      const fileData = file.raw
      this.loading = true
      getOrgInfo(fileData)
        .then(res => {
          const data = res?.data ?? {}
          this.editData.gua_entity_cert_no = data.reg_num || ''
          this.editData.gua_entity_corp = data.person
          this.editData.gua_entity = data.name
          this.editData.gua_entity_address = data.address
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleUploadRegister(files) {
      const attachment = arrayToString(files.map(it => it.url))
      this.editData.cert_attachment = attachment
      this.onSubmit()
    },
    handleUploadAttachment(files) {
      const attachment = arrayToString(files.map(it => it.url))
      this.$set(this.editData, 'attachment', attachment)
      this.submit()
    },
    uploadAttachment() {
      // 删除后若没重新添加附件会导致之前的附件在阿里云已删除
      if (this.$refs.attachment) {
        this.$refs.attachment.submit()
      } else {
        this.submit()
      }
    },
    getData() {
      if (!this.tableId) {
        this.personData = []
        return
      }
      this.loading = true
      Promise.all([
        this.$api.getData(
          this.$serviceName,
          'gua_person_list',
          { 'gua_contract_id.eq': this.tableId },
          { create_time: 'asc' }
        ),
      ])
        .then(([res]) => {
          this.personData = res?.data ?? []
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleBeforeSave(model) {
      model.customer_name = this.relatedData.customer_name
      model.customer_address = this.relatedData.address
      model.customer_phone = this.relatedData.mobile_no
      model.bank_name = this.entrustContract.bank_name
      model.entrust_bank_name = this.entrustContract.entrust_bank_name
      model.apply_funds = this.entrustContract.reply_funds
      model.loan_contract_no = this.entrustContract.loan_contract_no
      model.ensure_contract_no = this.entrustContract.ensure_contract_no
      // model.ensure_contract_name = this.entrustContract.ensure_contract_name
      model.gua_com_corp = this.entrustContract.accept_entrust_entity_corp
      model.sign_date = this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
      model.num_copes_per = model.num_copes_per_lower ? nzhToNum(model.num_copes_per_lower) : ''
      model.num_copes = model.num_copes_lower ? nzhToNum(model.num_copes_lower) : ''
      if (+model.gua_entity_type !== 1) {
        model.gua_entity_corp = ''
      }
      model.customer_related_id = this.queryId
      model.gua_method = 1
      return model
    },
    handleUploadFile() {
      const promises = this.personData.map(item => {
        const attach = item.cert_attachment ? arrayFromString(item.cert_attachment) : ''
        if (item.file) {
          if (attach) {
            this.deleteAttach.push(...attach)
          }
          return uploadOss({
            file: item.file,
            dir: `credit/contract/promise/${this.queryId}/`,
            type: 0,
          })
        } else {
          return Promise.resolve(attach?.[0] || '')
        }
      })
      return Promise.all(promises)
        .then(list => {
          list.forEach((attachment, index) => {
            const { file, url, ...data } = this.personData[index]
            data.cert_attachment = attachment ? arrayToString([attachment]) : arrayToString([])
            this.personData[index] = data
          })
          this.editData.cert_attachment = arrayToString(list.filter(item => item))
        })
        .finally(() => {
          deleteOss(this.deleteAttach)
        })
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.$refs.uploadRegister) {
            this.$refs.uploadRegister.submit()
          } else {
            this.saveLoading = true
            this.handleUploadFile().finally(() => {
              this.saveLoading = false
              this.onSubmit()
            })
          }
        } else {
          this.$message.error('输入错误，请重新输入！')
        }
      })
    },
    onSubmit() {
      this.personData = this.personData.map(item => {
        const { file, url, ...data } = item
        return data
      })
      if (this.tableId) {
        this.putData()
      } else {
        this.postData()
      }
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    addPerson(row = {}, index = -1) {
      if (index !== -1) {
        const attach = arrayFromString(row.cert_attachment)
        this.addAttach = row.url ? [{ url: row.url }] : [{ url: attach?.[0] ?? '' }]
      } else {
        this.addAttach = []
      }
      this.editIndex = index
      this.addVisible = true
      this.addData = { ...row }
    },
    deletePerson(index) {
      if (this.personData.length < 2) {
        return this.$message.warning('最少需添加一个反担保人')
      }
      const deleteData = this.personData.splice(index, 1)
      const data = deleteData?.[0] ?? {}
      if (data.cert_attachment) {
        const attach = arrayFromString(data.cert_attachment)
        this.deleteAttach.push(...attach)
      }
      if (data.url) {
        URL.revokeObjectURL(data.url)
      }
    },
    putData() {
      if (!this.queryId) {
        return
      }

      if (this.isSYSTEM || this.isRedo) {
        //系统后台重做重签合同
        this.editData.sign_status = this.signStatus
        this.editData.re_sign_type = 1
      }
      const data = this.handleBeforeSave(this.editData)

      if (+this.editData.gua_entity_type === 1) {
        this.saveLoading = true
        this.$api
          .updateData(this.$serviceName, this.tableName, this.tableId, data)
          .then(() => {
            this.handleSuccess()
          })
          .catch(() => {
            this.$message.error('修改失败！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.updatePerson()
      }
    },
    handleSuccess() {
      this.beforeClose()
      this.$emit('success', true)
      this.$message.success('保存成功')
    },
    updatePerson() {
      const slaveData = this.tableId
        ? this.personData.map(item => {
            item.gua_contract_id = this.tableId
            return item
          })
        : this.personData
      if (slaveData.length < 1) {
        return this.$message.warning('至少填入一名反担保人')
      }
      this.editData.gua_entity = slaveData.map(item => item.gua_person_name).join('、')
      this.editData.gua_entity_mobile = slaveData[0].gua_person_phone
      this.editData.gua_entity_cert_no = slaveData[0].id_card
      this.editData.gua_entity_address = slaveData[0].gua_person_address
      if (this.tableId) {
        this.editData.gua_contract_id = this.tableId
      }

      const formData = {
        masterTableInfo: JSON.stringify(this.editData),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'gua_person_list',
      }
      if (this.tableId) {
        this.saveLoading = true
        this.$api
          .relatedUpdate(this.$serviceName, formData)
          .then(() => {
            this.handleSuccess()
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.saveLoading = true
        this.$api
          .relatedBatch(this.$serviceName, formData)
          .then(() => {
            this.handleSuccess()
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    postData() {
      if (!this.queryId) {
        return
      }

      const data = this.handleBeforeSave(this.editData)
      if (this.isSYSTEM || this.isRedo) {
        //系统后台重做重签合同
        data.sign_status = 1
        data.re_sign_type = 2
      }
      if (+this.editData.gua_entity_type === 1) {
        this.saveLoading = true
        this.$api
          .addData(this.$serviceName, this.tableName, data)
          .then(() => {
            this.handleSuccess()
          })
          .catch(() => {
            this.$message.error('保存失败！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.updatePerson()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.input-td {
  background: #ffffee;
}
</style>
